use serde::{Serialize, Deserialize};
use crate::port_mapper::Error;
use std::fs::{File, OpenOptions};

#[derive(Serialize, Deserialize)]
pub struct ConfigItem {
    pub name: String,
    pub lst_addr: String,
    pub lst_port: u16,
    pub dst_addr: String,
    pub dst_port: u16,
    pub id: u32,
}

#[derive(Serialize, Deserialize)]
pub struct ConfigRoot {
    pub maps: Vec<ConfigItem>,
}

impl ConfigRoot {
    pub fn new() -> ConfigRoot {
        ConfigRoot {
            maps: Default::default(),
        }
    }
}

pub fn parse_from_file(path: &str) -> Result<ConfigRoot, Error> {
    let config_file = File::open(path)?;
    Ok(serde_json::de::from_reader(config_file)?)
}

pub fn save_to_file(path: &str, config: &ConfigRoot) -> Result<(), Error> {
    let config_file = OpenOptions::new()
                            .write(true)
                            .truncate(true)
                            .create(true).open(path)?;
    Ok(serde_json::ser::to_writer_pretty(config_file, config)?)
}
